/**
* @作者:陈博宇/邹蕴果
* @创建时间：2021/7/8
* @修改时间：2021/7/17
* @修改时间：2021/7/22
*/

<template>
	<view class="main">
		<!-- 头部状态栏 -->
		<view class="header">
			<img src="/static/xiangzulogo.png" style="width: 176rpx; height: 99rpx;" fit="cover" class="logo"
				@click="jumpToMain()">
			<view class="navitems">
				<el-badge :value="messageNum" class="navitem" hidden="messageNum==0">
					<view @click="jumpToMessage">消息</view>
				</el-badge>
				<view class="navitem" @click="logOut">退出登录</view>
			</view>
		</view>
		<!-- 主页面 -->
		<el-tabs class="tabs" :tab-position="tabPosition" type="border-card">
			<!-- 购物车界面 -->
			<el-tab-pane>
				<span slot="label"><i class="el-icon-date"></i> 我的购物车</span>
				<!-- 搜索框 -->
				<div class="searchWord">
					<div style="display: inline-block"> 全局搜索：</div>
					<el-input v-model="search" style="display: inline-block;width: 200px" placeholder="请输入搜索内容">
					</el-input>
				</div>
				<!-- 商品界面 -->
				<div id="goods">
					<el-table :data="tables" border style="width: 100%; margin-top: 20px"
						@selection-change="handleSelectionChange">
						<el-table-column type="selection" width="55">
						</el-table-column>
						<el-table-column prop="name" label="商品名" width="220">
						</el-table-column>
						<el-table-column prop="images" label="图片" width="100">
							<template slot-scope="scope">
								<img :src='"http://47.96.168.135:7388"+scope.row.src' style="width:60px;height:60px;" />
							</template>
						</el-table-column>
						<el-table-column prop="sort" label="类别">
						</el-table-column>
						<el-table-column prop="brand" label="品牌" width="120">
						</el-table-column>
						<el-table-column prop="paramete" label="配置">
						</el-table-column>
						<el-table-column prop="price" label="日租" width="100">
						</el-table-column>
						<el-table-column prop="shop" label="店铺">
						</el-table-column>
						<el-table-column label="操作" align="center" width="160">
							<template slot-scope="scope">
								<el-button size="mini" type="primary" @click="jumpToGoods(scope.row.id)">查看
								</el-button>
								<el-button size="mini" type="danger" @click="handleDelete(scope.row.itemId)">
									删除
								</el-button>
							</template>
						</el-table-column>
					</el-table>
				</div>
			</el-tab-pane>
			<!-- 地址界面 -->
			<el-tab-pane label="我的地址">
				<el-button type="primary" @click="addDialogVisible=true">添加地址</el-button>
				<!-- 添加地址对话框 -->
				<el-dialog title="添加地址" :visible.sync="addDialogVisible" width="47%" @close="addDialogClosed">
					<!-- 内容的主体区域 -->
					<el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="95px">
						<el-form-item label="地址信息" prop="add" size="mini">
							<v-region :town="true" v-model="selected" @values="regionChange"></v-region>
						</el-form-item>
						<el-form-item label="详细地址" prop="detailAdd">
							<el-input type="textarea" v-model="ruleForm.detailAdd"></el-input>
						</el-form-item>
						<el-form-item label="收货人姓名" prop="name">
							<el-input v-model="ruleForm.name"></el-input>
						</el-form-item>
						<el-form-item label="手机号码" prop="phoneNumber">
							<el-input type="text" oninput="value=value.replace(/[^\d]/g,'')"
								v-model.number="ruleForm.phoneNumber" autocomplete="off">
							</el-input>
						</el-form-item>
					</el-form>
					<!-- 底部区域 -->
					<span slot="footer" class="dialog-footer">
						<el-button @click="addDialogVisible = false">取 消</el-button>
						<el-button type="primary" @click="submitForm('ruleForm')">确 定</el-button>
					</span>
				</el-dialog>
				<!-- 地址列表 -->
				<view class="myAddress">
					<el-table :data="allAddressGet" border style="width: 100%; margin-top: 20px"
						@selection-change="handleSelectionChange" height="630">
						<el-table-column prop="receiverName" label="收货人" style="width: 10%;">
						</el-table-column>
						<el-table-column prop="province" label="所在地区">
							<template slot-scope="scope">
								<div>
									{{scope.row.province}}-{{scope.row.city}}-{{scope.row.town}}-{{scope.row.area}}
								</div>
							</template>
						</el-table-column>
						<el-table-column prop="detailInfo" label="详细地址" style="width: 10%;">
						</el-table-column>
						<el-table-column prop="phoneNum" label="手机号码">
						</el-table-column>
						<el-table-column label="操作" align="center">
							<template slot-scope="scope">
								<el-button size="mini" @click="showEditDialog(scope.row.id)">编辑</el-button>
								<el-button size="mini" type="danger" @click="addDelete(scope.row.id)">
									删除
								</el-button>
							</template>
						</el-table-column>
					</el-table>
				</view>
				<!-- 修改地址的对话框 -->
				<el-dialog title="修改地址" :visible.sync="editDialogVisible" width="47%" @close="editDialogClosed">
					<el-form :model="editAddForm" :rules="rules" ref="editAddFormRef" label-width="95px">
						<el-form-item label="地址信息" prop="editAdd" size="mini">
							<v-region :town="true" v-model="editAdd" @values="editRegionChange"></v-region>
						</el-form-item>
						<el-form-item label="详细地址" prop="detailAdd">
							<el-input type="textarea" v-model="editAddForm.detailAdd"></el-input>
						</el-form-item>
						<el-form-item label="收货人姓名" prop="name">
							<el-input v-model="editAddForm.name"></el-input>
						</el-form-item>
						<el-form-item label="手机号码" prop="phoneNumber">
							<el-input type="text" oninput="value=value.replace(/[^\d]/g,'')"
								v-model.number="editAddForm.phoneNumber" autocomplete="off">
							</el-input>
						</el-form-item>
					</el-form>
					<span slot="footer" class="dialog-footer">
						<el-button @click="editDialogVisible = false">取 消</el-button>
						<el-button type="primary" @click="editAddInfo">确 定</el-button>
					</span>
				</el-dialog>
			</el-tab-pane>
			<!-- 订单界面 -->
			<el-tab-pane label="我的订单">
				<!-- 搜索界面 -->
				<div class="searchWord">
					<div style="display: inline-block"> 全局搜索：</div>
					<el-input v-model="search" style="display: inline-block;width: 200px" placeholder="请输入搜索内容">
					</el-input>
				</div>
				<!-- 订单列表 -->
				<view>
					<el-table :data="Orders" style="width: 100%; margin-top: 20px" height="625" border
						:header-cell-style="{background:'#F5F7FA',color:'#606266'}" default-expand-all>
						<el-table-column type="expand">
							<template slot-scope="props">
								<el-form label-position="left" inline class="demo-table-expand">
									<el-form-item label="所属店铺:">
										<span>{{ props.row.shop }}</span>
									</el-form-item>
									<el-form-item label="品牌:">
										<span>{{ props.row.brand }}</span>
									</el-form-item>
									<el-form-item label="日租:">
										<span>{{ props.row.dailyRent }}</span>
									</el-form-item>
									<el-form-item label="租赁开始时间:">
										<span>{{ props.row.startDate }}</span>
									</el-form-item>
									<el-form-item label="商品分类:">
										<span>{{ props.row.category }}</span>
									</el-form-item>
									<el-form-item label="配置:">
										<span>{{ props.row.paramete }}</span>
									</el-form-item>
									<el-form-item label="数量:">
										<span>{{ props.row.num }}</span>
									</el-form-item>
									<el-form-item label="租赁结束时间:">
										<span>{{ props.row.endDate }}</span>
									</el-form-item>
								</el-form>
							</template>
						</el-table-column>
						<el-table-column label="日期" prop="date">
						</el-table-column>
						<el-table-column label="订单ID" prop="id">
						</el-table-column>
						<el-table-column label="图片">
							<template slot-scope="scope">
								<img :src="scope.row.src" style="width:50px;height:50px;" />
							</template>
						</el-table-column>
						<el-table-column label="商品名称" prop="name">
						</el-table-column>
						<el-table-column label="实付款" prop="pay" width="240">
							<template slot-scope="scope">
								<div>
									<div style="font-size: 18px;color: #ff3e3e;">
										¥{{scope.row.pay}}
									</div>
									<div style="font-size: 10px">
										(商品:¥{{scope.row.rent}}+押金:¥{{scope.row.deposit}})
									</div>
								</div>
							</template>
						</el-table-column>
						<el-table-column label="状态" prop="state" :filters="[{ text: '待发货', value: '待发货' }, { text: '待收货', value: '待收货' }, { text: '租赁中', value: '租赁中'
							}, { text: '待归还', value: '待归还' }, { text: '归还中', value: '归还中' }, { text: '已完成', value: '已完成' }]"
							:filter-method="filterTag" filter-placement="bottom-end">
							<template slot-scope="scope">
								<el-tag :type="scope.row.type" :effect="scope.row.effect" disable-transitions>
									{{scope.row.state}}
								</el-tag>
							</template>
						</el-table-column>
						<el-table-column label="操作">
							<template slot-scope="scope">
								<el-button size="mini" type="primary" @click="jumpToOrder(scope.row.id)">查看
								</el-button>
								<el-button size="mini" @click="jumpToOrder(scope.row.id)">编辑</el-button>
							</template>
						</el-table-column>
					</el-table>
				</view>
			</el-tab-pane>
			<!-- 个人信息 -->
			<el-tab-pane label="我的信息">
				<div style="margin: 20px;"></div>
				<el-form label-position="left" label-width="80px" :model="formLabelAlign">
					<el-form-item label="头像">
						<image class="userimg" :src="imgsrc"></image>
						<el-button type="text" @click="changeimg">改变头像</el-button>
					</el-form-item>
					<el-form-item label="昵称">
						<view v-show="show" class="nickinput">{{this.nickname}}</view>
						<el-input v-model="nickname" v-show="!show" class="nickinput"></el-input>
						<el-button @click="changeshow(1)">修改昵称</el-button>
					</el-form-item>
					<el-form-item label="邮箱">
						<view v-show="show2" class="nickinput">{{this.mailAddress}}</view>
						<el-input v-model="mailAddress" v-show="!show2" class="nickinput"></el-input>
						<el-button @click="changeshow(2)">修改邮箱</el-button>
					</el-form-item>
					<el-form-item label="手机号">
						<view v-show="show3" class="nickinput">{{this.phone}}</view>
						<el-input v-model="phone" v-show="!show3" class="nickinput"></el-input>
						<el-button @click="changeshow(3)">修改手机号</el-button>
					</el-form-item>
					<el-form-item>
						<el-button @click="submit">确定改变</el-button>
					</el-form-item>
				</el-form>
			</el-tab-pane>
		</el-tabs>
	</view>

</template>

<script>
	export default {

		onLoad() {
			if (!this.$cookies.isKey("userId")) {
				this.$alert('您还未登录，请先登录！', '错误', {
					confirmButtonText: '确定',
				});
				uni.redirectTo({
					url: "../index/UserLoginIndex"
				})
			}
			this.$axios({
				method: 'get',
				url: 'Customer/getCustomerById?Id=' + this.$cookies.get("userId")
			}).then(res => {
				this.mailAddress = res.data.date.email
				this.userid = res.data.date.id
				this.phone = res.data.date.phoneNum
				this.nickname = res.data.date.name
				this.imgsrc = 'http://47.96.168.135:7388/' + res.data.date.faceUrl
				this.$cookies.set("userName", this.nickname, "1h")
				this.$cookies.set("userId", this.userid, "1h")
				this.$cookies.set("userFaceImg", res.data.date.faceUrl, "1h")
			})
		},

		mounted: function() {
			this.addMyCart();
			this.getAddress();
			this.getOrder();
		},

		methods: {

			//receive selected region data
			regionChange(data) {
				this.ruleForm.add = data
			},
			editRegionChange(data) {
				this.editAddForm.add = data
			},

			// 添加地址
			submitForm(formName) {
				this.$refs[formName].validate((valid) => {
					if (valid) {
						this.$axios({
							method: "post",
							url: "/Address/addAddress",
							data: {
								"area": this.ruleForm.add.area.value,
								"areaNum": this.ruleForm.add.area.key,
								"city": this.ruleForm.add.city.value,
								"cityNum": this.ruleForm.add.city.key,
								"customerId": this.$cookies.get("userId"),
								"detailInfo": this.ruleForm.detailAdd,
								"phoneNum": this.ruleForm.phoneNumber,
								"province": this.ruleForm.add.province.value,
								"provinceNum": this.ruleForm.add.province.key,
								"receiverName": this.ruleForm.name,
								"town": this.ruleForm.add.town.value,
								"townNum": this.ruleForm.add.town.key,
							}
						}).then((res) => {
							this.$message.success('添加地址成功！')
							// 隐藏添加用户的对话框
							this.addDialogVisible = false;
							this.resetForm('ruleForm');
							// 重新获取用户列表数据
							this.getAddress();
						});
					} else {
						return false;
					}
				});
				this.resetForm('ruleForm');
			},
			// 重置表格内容
			resetForm(formName) {
				this.$refs[formName].resetFields();
				this.selected.province = '';
				this.selected.city = '';
				this.selected.town = '';
				this.selected.area = '';
			},
			// 监听添加用户对话框的关闭事件
			addDialogClosed() {
				this.resetForm('ruleForm');
			},
			// 获取购物车
			async addMyCart() {
				var that = this;
				await this.$axios({
					methods: 'get',
					url: '/Customer/MyShoppingCart?CustomerName=' + this.$cookies.get("userName"),
				}).then(res => {
					that.sku = res.data.date
				}).catch(err => {

				})
				this.sku.forEach((item, index) => {
					let current = {
						itemId: item.id,
						id: item.sku.id,
						name: item.sku.name,
						src: item.sku.skuImages[0].url,
						sort: '数码/手机',
						brand: '华为',
						paramete: item.sku.skuSpecificationOptions[item.specificationIndex].value,
						stock: item.sku.skuSpecificationOptions[item.specificationIndex].stock,
						price: item.sku.skuSpecificationOptions[item.specificationIndex].price,
						shop: item.sku.storeName
					}
					this.newTableData.push(current);
				})
			},
			// 跳转到商品详情
			jumpToGoods(id) {
				uni.navigateTo({
					url: "../index/GoodsDetail?id=" + id
				})
			},
			// 获取地址
			async getAddress() {
				var that = this;
				await this.$axios({
					methods: 'get',
					url: '/Address/getAllByCustomerName?CustomerName=' + this.$cookies.get("userName"),
				}).then(res => {
					that.allAddressGet = res.data.date
				}).catch(err => {})
			},

			// 展示编辑地址的对话框
			showEditDialog(id) {
				this.allAddressGet.forEach((item, index) => {
					if (item.id === id) {
						this.editAdd.province = item.provinceNum.toString();
						this.editAdd.city = item.cityNum.toString();
						this.editAdd.town = item.townNum.toString();
						this.editAdd.area = item.areaNum.toString();
						this.editAddForm.id = item.id;
						this.editAddForm.detailAdd = item.detailInfo;
						this.editAddForm.name = item.receiverName;
						this.editAddForm.phoneNumber = item.phoneNum;
					}
				})
				this.editDialogVisible = true
			},
			// 监听修改地址对话框的关闭
			editDialogClosed() {
				this.$refs.editAddFormRef.resetFields()
			},
			// 修改用户信息并且提交
			editAddInfo() {
				this.$refs.editAddFormRef.validate((valid) => {
					if (valid) {
						this.$axios({
							method: "post",
							url: "/Address/modifyAddress",
							data: {
								"id": this.editAddForm.id,
								"area": this.editAddForm.add.area.value,
								"areaNum": this.editAddForm.add.area.key,
								"city": this.editAddForm.add.city.value,
								"cityNum": this.editAddForm.add.city.key,
								"customerId": this.$cookies.get("userId"),
								"detailInfo": this.editAddForm.detailAdd,
								"phoneNum": this.editAddForm.phoneNumber,
								"province": this.editAddForm.add.province.value,
								"provinceNum": this.editAddForm.add.province.key,
								"receiverName": this.editAddForm.name,
								"town": this.editAddForm.add.town.value,
								"townNum": this.editAddForm.add.town.key,
							}
						}).then((res) => {
							this.$message.success('修改地址成功！')
							// 隐藏添加用户的对话框
							this.editDialogVisible = false;
							// 重新获取用户列表数据
							this.getAddress();
						});
					} else {
						return false;
					}
				})
			},
			// 删除地址
			addDelete(id) {
				this.$confirm('此地址将永久删除, 是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					var that = this;
					this.$axios({
						methods: 'get',
						url: '/Address/deleteAddress?id=' + id,
					}).then(() => {
						this.$message({
							type: 'success',
							message: '删除成功!'
						});
						this.getAddress();
					}).catch(err => {})

				}).catch(() => {
					this.$message({
						type: 'info',
						message: '已取消删除'
					});
				});
			},
			// 获取订单
			async getOrder() {
				var that = this;
				await this.$axios({
					methods: 'get',
					url: '/Order/getOrdersByCustomerName?CustomerName=' + this.$cookies.get("userName"),
				}).then(res => {
					that.allOrderGet = res.data.date
				}).catch(err => {})
				this.allOrderGet.forEach((item, index) => {
					let current = {
						date: item.orderDate,
						startDate: item.leaseStartTime,
						endDate: item.leaseEndTime,
						id: item.id,
						src: "http://47.96.168.135:7388" + item.sku.skuImages[0].url,
						name: item.sku.name,
						brand: item.brandName,
						paramete: item.sku.skuSpecificationOptions[item.specificationIndex].value,
						dailyRent: item.sku.skuSpecificationOptions[item.specificationIndex].price,
						num: item.num,
						pay: item.sumOfMoney,
						rent: item.sumOfRent,
						deposit: item.sku.skuSpecificationOptions[item.specificationIndex].deposit,
						state: item.state,
						type: '',
						effect: '',
						category: item.categoryName + '/' + item.channelName,
						shop: item.sku.storeName
					}
					switch (current.state) {
						case '待发货':
							current.type = 'warning';
							current.effect = 'dark';
							break;
						case '待收货':
							current.effect = 'dark';
							break;
						case '租赁中':
							current.type = 'success';
							break;
						case '待归还':
							current.type = 'danger';
							current.effect = 'dark';
							break;
						case '已完成':
							current.type = 'success';
							current.effect = 'dark';
							break;
					}
					this.newAllOrderGet.push(current);
				})
			},
			// 跳转到具体订单
			jumpToOrder(id) {
				uni.navigateTo({
					url: "../index/customerOrder?thatOrderId=" + id
				})
			},
			// 修改个人信息
			changeshow(val) {
				if (val == 1) {
					this.show = !this.show
				} else if (val == 2) {
					this.show2 = !this.show2
				} else if (val == 3) {
					this.show3 = !this.show3
				}
			},
			// 提交个人信息修改
			submit() {
				uni.uploadFile({
					url: 'http://47.96.168.135:7388/Customer/ModifyTheInfo',
					filePath: this.imgsrc,
					name: 'face',
					formData: {
						id: this.userid,
						name: this.nickname,
						email: this.mailAddress,
						phoneNum: this.phone
					},
					success: (uploadFileRes) => {}
				});
				Location.reload()
			},
			// 换头像
			changeimg() {
				uni.chooseImage({
					count: 1,
					success: (res) => {
						this.imgsrc = res.tempFilePaths[0]
					}
				})
			},

			handleSelectionChange(val) {
				this.multipleSelection = val;
			},
			// 删除购物车内容
			handleDelete(id) {
				this.$confirm('此操作将永久将该商品从购物车中移除, 是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.$axios({
						methods: 'get',
						url: '/Customer/deleteShoppingCart?ConcreteSKUId=' + id + '&Name=' + this.$cookies
							.get("userName"),
					}).then(res => {
						this.$message({
							type: 'success',
							message: '删除成功!'
						});
						this.newTableData = [];
						this.addMyCart();
					}).catch(err => {})
				}).catch(() => {
					this.$message({
						type: 'info',
						message: '已取消删除'
					});
				});
			},

			filterTag(value, row) {
				return row.state === value;
			},
			// 跳转到主页
			jumpToMain() {
				uni.redirectTo({
					url: "../index/Userindex"
				})
			},

		},

		data() {
			return {
				addDialogVisible: false,

				sku: [],
				newTableData: [],

				allAddressGet: [],

				allOrderGet: [],
				newAllOrderGet: [],

				search: '',
				tabPosition: 'left',

				show2: true,
				show3: true,
				phone: 18581891011,
				mailAddress: ' ',
				nickname: '杰哥',
				userid: 0,
				show: true,
				imgsrc: '',
				formLabelAlign: {
					name: '',
					region: '',
					type: ''
				},

				selected: {
					province: '',
					city: '',
					area: '',
					town: ''
				},

				ruleForm: {
					name: '',
					add: '',
					detailAdd: '',
					phoneNumber: ''
				},


				rules: {
					name: [{
						required: true,
						message: '请输入收货人姓名',
						trigger: 'blur'
					}],
					add: [{
						required: true,
						message: '请选择地址信息',
						trigger: 'blur'
					}],
					detailAdd: [{
						required: true,
						message: '请填写详细地址',
						trigger: 'blur'
					}],
					phoneNumber: [{
						required: true,
						message: '手机号码不能为空',
						trigger: 'blur'
					}]
				},

				// 控制修改用户对话框的显示与隐藏，默认为隐藏
				editDialogVisible: false,
				// 查询到的用户信息对象
				editAddForm: {
					id: '',
					add: '',
					name: '',
					detailAdd: '',
					phoneNumber: ''
				},
				editAdd: {
					province: '350000',
					city: '350100',
					area: '350104',
					town: '350104008'
				},

			};
		},

		computed: {
			// 模糊搜索
			tables() {
				const search = this.search
				if (search) {
					// filter() 方法创建一个新的数组，新数组中的元素是通过检查指定数组中符合条件的所有元素。
					// 注意： filter() 不会对空数组进行检测。
					// 注意： filter() 不会改变原始数组。
					return this.newTableData.filter(data => {
						// some() 方法用于检测数组中的元素是否满足指定条件;
						// some() 方法会依次执行数组的每个元素：
						// 如果有一个元素满足条件，则表达式返回true , 剩余的元素不会再执行检测;
						// 如果没有满足条件的元素，则返回false。
						// 注意： some() 不会对空数组进行检测。
						// 注意： some() 不会改变原始数组。
						return Object.keys(data).some(key => {
							// indexOf() 返回某个指定的字符在某个字符串中首次出现的位置，如果没有找到就返回-1；
							// 该方法对大小写敏感！所以之前需要toLowerCase()方法将所有查询到内容变为小写。
							return String(data[key]).toLowerCase().indexOf(search) > -1
						})
					})
				}
				return this.newTableData
			},

			Orders() {
				const search = this.search
				if (search) {
					return this.newAllOrderGet.filter(data => {
						return Object.keys(data).some(key => {
							return String(data[key]).toLowerCase().indexOf(search) > -1
						})
					})
				}
				return this.newAllOrderGet
			}
		}
	}
</script>

<style>
	.main {
		display: flex;
		flex-direction: column;
		position: absolute;
		width: 100%;
		float: left;
	}

	/* 顶栏style */
	.header {
		width: 100%;
		height: 99rpx;
		display: flex;
		box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
		position: relative;
		z-index: 10;
	}

	.logo {
		margin-left: 5%;
	}

	.navitems {
		margin: auto;
		display: flex;
		margin-right: 5%;
	}

	.navitem {
		font-size: 15px;
		margin-left: 50rpx;
	}

	.tabs {
		height: 706px;
	}

	.delete {
		transform: translateX(875px);
	}

	.breadcrumb {
		width: 100%;
		background-color: #EEEEEE;
		height: 30px;
	}

	.breadcrumb_content {
		display: flex;
		width: 100%;
	}

	.newAddress {
		display: flex;
		width: 50%;
		margin-top: 20px
	}

	//订单
	.demo-table-expand {
		font-size: 0;
	}

	.demo-table-expand label {
		width: 90px;
		color: #ff0000;
	}

	.demo-table-expand .el-form-item {
		margin-right: 0;
		margin-bottom: 0;
		width: 23%;
	}

	.userimg {
		width: 50rpx;
		height: 50rpx;
		border-radius: 50%;
	}

	.nickinput {
		width: 50%;
		float: left;
	}
</style>
